package com.baijiayun.live.ui.speakpanel

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.lifecycle.LifecycleObserver
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.activity.LiveRoomBaseActivity
import com.baijiayun.live.ui.activity.LiveRoomRouterListener
import com.baijiayun.live.ui.hasParentView
import com.baijiayun.live.ui.speakerlist.item.LocalItem
import com.baijiayun.live.ui.speakerlist.item.Playable
import com.baijiayun.live.ui.speakerlist.item.SwitchableType
import com.baijiayun.livecore.models.launch.LPAwardConfig
import com.baijiayun.livecore.utils.LPRxUtils
import com.baijiayun.livecore.viewmodels.impl.LPSpeakQueueViewModel
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.widgets.dialog.AwardPopupWindow
import com.baijiayun.liveuibase.widgets.dialog.ThemeMaterialDialogBuilder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.bjy_layout_item_video.view.*

/**
 * Created by yongjiaming on 2019-10-18
 * Describe:
 */
class LocalVideoItem(rootView: ViewGroup, routerListener: LiveRoomRouterListener) : LocalItem(rootView, routerListener), Playable, LifecycleObserver {
    private var disposableOfCameraOn: Disposable? = null
    private var awardPopupWindow: AwardPopupWindow? = null
    private val videoStatusTv by lazy {
        container.findViewById<TextView>(R.id.item_status_placeholder_tv)
    }
    private val videoStatusContainer by lazy {
        container.findViewById<View>(R.id.item_status_placeholder_ll)
    }
    private val videoStatusIv by lazy {
        container.findViewById<ImageView>(R.id.item_status_placeholder_iv)
    }

    init {
        container = LayoutInflater.from(context).inflate(R.layout.bjy_layout_item_video, rootView, false) as ViewGroup
        videoContainer = container.item_local_speaker_avatar_container
        speakerName = container.item_local_speaker_name
        refreshNameTable()
        registerClickEvent(container)
        initAward()
        container.item_award_container.setOnClickListener {
            if (awardPopupWindow != null) {
                // 多种，弹窗
                awardPopupWindow!!.run {
                    if (isShowing) {
                        dismiss()
                    } else {
                        show(it)
                    }
                }
            }
        }
    }

    private fun initAward() {
        val awardConfigs: Array<LPAwardConfig> = routerListener.liveRoom.awardConfigs
                ?: return
        var enableAwardTypeCount = 0
        var availableAward: LPAwardConfig? = null
        for (lpAwardConfig in awardConfigs) {
            if (lpAwardConfig.isEnable == 1) {
                availableAward = lpAwardConfig
                enableAwardTypeCount++
            }
        }
        if (enableAwardTypeCount <= 1 && availableAward != null) {
            // 仅一种启用，使用对应logo
            container.item_award_icon.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.base_ic_award_like))
            // 保存 当前 LPAwardConfig
        } else {
            // 使用钻石
            container.item_award_icon.setImageResource(R.drawable.base_ic_video_award_default)
            // 初始化 AwardPopupWindow
            awardPopupWindow = AwardPopupWindow(context, routerListener.liveRoom.currentUser, null)
        }
    }

    //也可以在这里初始化，但是注意生命周期,这时候子类属性没有初始化
    override fun initView() {
        disposableOfCameraOn = recorder.observableOfCameraOn
                .filter { liveRoom.speakQueueVM.enableAttachPhoneCamera() }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { b: Boolean ->
                    shouldStreamVideo = b
                    if (b) {
                        showVideoOpen()
                    } else {
                        showVideoClose()
                        //关闭扫码直播后开启本地视频
                        if (enableLocalCamera) {
                            enableLocalCamera = false
                            routerListener.attachLocalVideo()
                        }
                        //外接设备关闭后，关闭本地摄像头，但是数据没回调外层，导致item没被移除
                        //音视频关闭而且不是主讲,从列表中移除item
                        if (!isPresenterVideo() && !TextUtils.isEmpty(qrCodeUrl) && hasParentView(this)) {
                            routerListener.detachLocalVideo()
                            qrCodeUrl = ""
                        }
                    }
                    //开关外接设备选项会变化关闭存在的dialog
                    if (qrCodeDialog?.isAdded == true) {
                        qrCodeDialog.dismissAllowingStateLoss()
                    }
                    if (dialog?.isShowing == true) {
                        dialog.dismiss()
                    }
                }
    }

    override fun switchPPTVideoSync() {
        if (liveRoom.isSyncPPTVideo && (liveRoom.isTeacherOrAssistant || liveRoom.isGroupTeacherOrAssistant)
            && isPresenterVideo() && liveRoom.isClassStarted) {
            showSwitchDialog()
        } else {
            switch2MaxScreenLocal()
        }
    }

    override fun enableClearScreen(): Boolean = true

    override fun getSwitchableType(): SwitchableType = if (isPresenterVideo()) {
        SwitchableType.MainItem
    } else {
        SwitchableType.SpeakItem
    }

    private fun isPresenterVideo(): Boolean {
        if (identity == LPSpeakQueueViewModel.FAKE_MIX_STREAM_USER_ID) {
            return true
        }
        if (routerListener.liveRoom.presenterUser == null) {
            return false
        }
        return identity == routerListener.liveRoom.presenterUser.userId
    }

    private fun switch2MaxScreenLocal() {
        super.switchPPTVideoSync()
    }

    private fun switch2MaxScreenSync() {
        liveRoom.requestPPTVideoSwitch(isPresenterVideo())
        switch2MaxScreenLocal()
    }

    override fun hideNickName(hide: Boolean) {
        super.hideNickName(hide)
        speakerName?.visibility = if (hide) View.GONE else View.VISIBLE
    }

    override fun addOpenVideoOpts(options: MutableList<String>) {
        super.addOpenVideoOpts(options)
        options.add(getString(R.string.live_open_video))
    }

    private fun showSwitchDialog() {
        if (context == null || context !is LiveRoomBaseActivity) {
            return
        }
        if (context.isFinishing || context.isDestroyed) {
            return
        }
        context.let {
            ThemeMaterialDialogBuilder(it)
                    .title(getString(R.string.live_exit_hint_title))
                    .content(getString(R.string.live_pad_sync_video_ppt))
                    .positiveText(R.string.live_pad_switch_sync)
                    .negativeText(R.string.live_pad_switch_local)
                    .negativeColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(it, R.attr.base_theme_dialog_negative_text_color))
                    .onPositive { _, _ -> switch2MaxScreenSync() }
                    .onNegative { _, _ -> switch2MaxScreenLocal() }
                    .show()
        }
    }

    override fun getView(): ViewGroup = container

    override fun showVideoClose() {
        videoContainer?.removeAllViews()
        videoStatusContainer?.visibility = View.VISIBLE
        videoStatusTv?.text = getString(R.string.pad_camera_closed)
        videoStatusIv?.setImageResource(R.drawable.base_ic_video_camera_mute)
    }

    fun resetOnStopState() {
        onStop()
        attachVideoOnResume = true
        routerListener.liveRoom.onlineUserVM.updateMediaState()
    }

    override fun showVideoOpen() {
        super.showVideoOpen()
        cameraView?.run {
            videoContainer?.removeAllViews()
            videoContainer?.addView(this)
        }
        videoStatusContainer?.visibility = View.GONE
    }

    private fun getString(@StringRes resId: Int) = context.getString(resId)

    override fun notifyAwardChange(count: Int) {
        if (count > 0) {
            container.item_award_container.visibility = View.VISIBLE
            container.item_award_count.text = count.toString()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LPRxUtils.dispose(disposableOfCameraOn)
    }
}